#!/usr/bin/python 


import sys



def words(filename):
  count = {}  
  input_file = open(filename, 'r')
  for line in input_file:
    words = line.split()
    for word in words:
      word = word.lower()
      if not word in count:
        count[word] = 1
      else:
        count[word] = count[word] + 1
  input_file.close() 
  return count


def print_words(filename):
  """Prints one per line '<word> <count>' sorted by word for the given file."""
  count = words(filename)
  words = sorted(count.keys())
  for word in words:
    print word, count[word]


def get_count(count_tuple):
  """Returns the count from a dict word/count tuple  -- used for custom sort."""
  return count_tuple[1]


def print_top(filename):
  """Prints the top count listing for the given file."""
  count = words(filename)

  items = sorted(count.items(), key=get_count, reverse=True)

  for item in items[:20]:
    print item[0], item[1]


def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'
    sys.exit(1)

  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
    print_words(filename)
  elif option == '--topcount':
    print_top(filename)
  else:
    print 'unknown option: ' + option
    sys.exit(1)

if __name__ == '__main__':
  main()
